package fge;

import com.mxgraph.model.mxCell;
import java.io.*;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

//public class HierarchyModel extends TreeModelSupport implements TreeModel, Serializable {
public class TreeHierarchyModel implements TreeModel, Serializable {

	mxCell root;
	protected EventListenerList listenerList = new EventListenerList();

	public TreeHierarchyModel(mxCell _root) {
		this.root = _root;
	}

	public void addTreeModelListener(TreeModelListener listener) {
		listenerList.add(TreeModelListener.class, listener);
	}

	public void removeTreeModelListener(TreeModelListener listener) {
		listenerList.remove(TreeModelListener.class, listener);
	}

	public void reload() {
		// Need to duplicate the code because the root can formally be
		// no an instance of the TreeNode.
		int n = getChildCount(root);
		int[] childIdx = new int[n];
		Object[] children = new Object[n];

		for (int i = 0; i < n; i++) {
			childIdx[i] = i;
			children[i] = getChild(root, i);
		}

		fireTreeStructureChanged(this, new Object[]{root}, childIdx, children);
	}

	/**
	 * fireTreeStructureChanged
	 * 
	 * @param source the node where the model has changed
	 * @param path the path to the root node
	 * @param childIndices the indices of the affected elements
	 * @param children the affected elements
	 */
	protected void fireTreeStructureChanged(Object source, Object[] path,
			int[] childIndices, Object[] children) {
		TreeModelEvent event = new TreeModelEvent(source, path, childIndices,
				children);
		TreeModelListener[] listeners = getTreeModelListeners();

		for (int i = listeners.length - 1; i >= 0; --i) {
			listeners[i].treeStructureChanged(event);
		}
	}

	public TreeModelListener[] getTreeModelListeners() {
		return (TreeModelListener[]) listenerList.getListeners(TreeModelListener.class);
	}

	@Override
	public Object getRoot() {
		return this.root;
	}

	public Object getChild(Object parent, int index) {
		if (parent instanceof Fcomponent) {
			Fcomponent parentcell = (Fcomponent) parent;
			return parentcell.getChildComponents().get(index);
		} else {
			mxCell parentcell = (mxCell) parent;
			return parentcell.getChildAt(index);
		}
	}

	public int getChildCount(Object parent) {
		if (parent instanceof Fcomponent) {
			Fcomponent parentcell = (Fcomponent) parent;
			return parentcell.getChildComponents().size();
		} else {
			mxCell parentcell = (mxCell) parent;
			return parentcell.getChildCount();
		}
	}

	public boolean isLeaf(Object node) {
		return (this.getChildCount(node) == 0);
	}

	@Override
	public void valueForPathChanged(TreePath path, Object newValue) {
	}

	public int getIndexOfChild(Object parent, Object child) {
		mxCell parentcell = (mxCell) parent;
		mxCell childcell = (mxCell) child;
		return parentcell.getIndex(childcell);
	}
}
